<?php

namespace App\Jobs;

use App\Model\Good;
use App\Model\PurchaseOrderDetail;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;

class PurchaseOrderDownloadGoodImageJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    protected $purchaseOrderDetailId;

    protected $goodId;

    /**
     * Create a new job instance.
     *
     * @param array $asinArr
     */
    public function __construct(int $purchaseOrderDetailId, int $goodId)
    {
        //
        $this->purchaseOrderDetailId = $purchaseOrderDetailId;
        $this->goodId = $goodId;
    }

    /**
     * Execute the job.
     *
     * @return bool
     * @throws \Exception
     */
    public function handle()
    {

        if ($this->attempts() > 3) {
            return;
        }
        $purchaseOrderDetail = PurchaseOrderDetail::query()->find($this->purchaseOrderDetailId);
        $purchaseOrderDetail->has_handle = 1;

        $good = Good::query()->find($this->goodId, ['goods_img_url']);

        if (!$good) {
            return $purchaseOrderDetail->save();
        }

        // 保存文件
        $filename = md5($good->goods_img_url) . '.jpg';
        $path = 'goods/' . $filename;

        if (Storage::disk('local')->exists($path)) {
            $purchaseOrderDetail->img_path = $path;
            return $purchaseOrderDetail->save();
        }

        $client = new Client(['base_uri' => 'http://img.susan.jiandanshang.com']);
        $response = $client->get('/upload/w_66/' . $good->goods_img_url);

        if ($response->getStatusCode() != 200) {

            return $purchaseOrderDetail->save();
        }

        if (Storage::disk('local')->put($path, $response->getBody()->getContents())) {
            $purchaseOrderDetail->img_path = $path;
            return $purchaseOrderDetail->save();
        }

        return $purchaseOrderDetail->save();
    }

}
